<?php
namespace app\controller;

use think\facade\View;
use app\model\ADdnsIpRuleServerApi;
 
 class Index
 {
     public function index()
     {
         View::assign('name', '欢迎使用 ThinkPHP 6！');
         return View::fetch('index');
     }

     public function api()
     { 
        return View::fetch('api');
     }

     public function getlogin() {  
        $token = bin2hex(random_bytes(32));  
        $postData = json_decode(file_get_contents('php://input'), true); 
        if(trim($postData['username']) == 'user123' && trim($postData['password']) == 'admin123'){
            $this->ajaxReturn(['status' => 'success', 'username' =>'user123','password' => 'admin123'], 'json'); 
        }else{
            $this->ajaxReturn(['status' => 'error', 'data' =>[],'token' => ''], 'json'); 
        } 
    }
 
     public function getAllIps()
     {
         $batchSize = 1000;
 
         // 使用模型类进行数据查询
         $existingIps = ADdnsIpRuleServerApi::field('server_addr')
             ->limit($batchSize)
             ->select()
             ->toArray();
 
         // 获取数据总量
         $total = ADdnsIpRuleServerApi::count();
 
         // 分批次查询
         $totalBatches = ceil($total / $batchSize);
         for ($i = 0; $i < $totalBatches; $i++) {
             $offset = $i * $batchSize;
             $batchIps = ADdnsIpRuleServerApi::field('server_addr')
                 ->limit($offset, $batchSize)
                 ->select()
                 ->toArray();
         }
     }
     public function getIpData()
     { 
         
         // 使用模型获取 IP 数据
         $ipData = ADdnsIpRuleServerApi::order('is_main_addr', 'desc')
             ->order('update_time', 'desc')
             ->field('id, server_addr, is_main_addr, server_id, create_time, update_time, rent_time, status')
             ->select()
             ->toArray();
 
          print_r($ipData);exit();
         // 统计每个 `server_id` 对应的 IP 数量
         $ruleIpCount = [];
         foreach ($ipData as $item) {
             $server_id = $item['server_id'];
             if (!isset($ruleIpCount[$server_id])) {
                 $ruleIpCount[$server_id] = 0;
             }
             $ruleIpCount[$server_id]++;
         }
 
         // 初始化存储分组的 IP 数据
         $groupedData = [];
         $ruleServerCount = [];
 
         // 按房间号（如 303、302）进行分组
         foreach ($ipData as &$item) {
             $room = $item['server_id']; // 假设 `server_id` 是房间号
             $item['rule_name'] = $room;
             $groupId = $item['server_id'];
 
             // 初始化每个房间的数据结构
             if (!isset($groupedData[$room])) {
                 $groupedData[$room] = [];
             }
 
             if (!isset($groupedData[$room][$groupId])) {
                 // 初始化该组的时间和 IP 列表
                 $groupedData[$room][$groupId] = [
                     'ruleName' => $room,
                     'group' => $groupId,
                     'time' => $item['rent_time'],
                     'ips' => [],
                     'count' => 0,
                 ];
             }
 
             // 将 IP 和其主 IP 标记添加到对应的组
             $groupedData[$room][$groupId]['ips'][] = [
                 'ip' => $item['server_addr'],
                 'is_main_addr' => $item['is_main_addr'],
                 'status' => $item['status']
             ];
             $groupedData[$room][$groupId]['count'] = count($groupedData[$room][$groupId]['ips']);
             $ruleServerCount[$room] = count($groupedData[$room]);
         }
 
         // 按数量排序
         arsort($ruleIpCount);
         arsort($ruleServerCount);
 
         // 检查是否需要导出数据
         $export = Request::get('export', 0, 'intval');
         if ($export) {
             $this->exportDataToExcelOne($groupedData);
         } else {
             return json([
                 'status' => 'success',
                 'data' => $groupedData,
                 'allData' => $ipData,
                 'ruleIpCount' => $ruleIpCount,
                 'ruleServerCount' => $ruleServerCount,
             ]);
         }
     }
 
     public function ip_manage_add()
     { 
         if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
             http_response_code(200);
             exit;
         }
 
         $postData = json_decode(file_get_contents('php://input'), true);
         $serverAddr = !empty($postData['serverAddr']) ? $postData['serverAddr'] : ''; 
         $serverAddrOne = !empty($postData['serverAddrOne']) ? trim($postData['serverAddrOne']) : '';  
 
         // 获取最大 server_id
         $max_id = ADdnsIpRuleServerApi::max('server_id');
         $serverId = $max_id + 1;
 
         $Server_addr = $this->dealWords($serverAddr);
         $Server_addr['-1'] = $serverAddrOne;  
 
         if (empty($Server_addr)) {
             return $this->ajaxReturn([
                 'status' => 'error', 
                 'message' => '上传IP不能为空!',
                 'notIp' => [],
                 'duplicateIp' => []
             ], 'json'); 
         }
 
         $Server_addr = array_filter($Server_addr); 
 
         // 正则校验 IP
         $ipv4Pattern = '/^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/';
         $ipv6Pattern = '/^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/';
 
         $notIp = [];
         $duplicateIp = [];
         $insertData = [];
         $time = time();
 
         // 获取已存在的 IP
         $existingIps = ADdnsIpRuleServerApi::column('server_addr');
         $existingIps = array_flip($existingIps);
 
         foreach ($Server_addr as $k => $ip) {
             if (!preg_match($ipv4Pattern, $ip) && !preg_match($ipv6Pattern, $ip)) {
                 $notIp[] = $ip;
                 break;
             }
 
             if (isset($existingIps[$ip])) {
                 $duplicateIp[] = $ip;
                 break;
             }
 
             $isMain = $k === -1 ? 2 : 0;
 
             $insertData[] = [
                 'server_id' => $serverId,
                 'is_main_addr' => $isMain,
                 'server_addr' => $ip,
                 'create_time' => $time,
                 'update_time' => $time,
             ];
         }
 
         if (count($notIp) > 0 || count($duplicateIp) > 0) {
             return $this->ajaxReturn([
                 'status' => 'error',
                 'message' => '添加 IP 地址失败',
                 'notIp' => $notIp,
                 'duplicateIp' => $duplicateIp
             ], 'json');
         }
 
         if (!empty($insertData)) {
             $result = ADdnsIpRuleServerApi::insertAll($insertData);
 
             if ($result) {
                 return $this->ajaxReturn([
                     'status' => 'success',
                     'message' => 'IP 地址添加成功',
                     'notIp' => $notIp,
                     'duplicateIp' => $duplicateIp
                 ], 'json');
             }
         }
     }

     protected function ajaxReturn($data, $type = '', $json_option = 0)
     {
         if (empty($type)) {
             $type = C('DEFAULT_AJAX_RETURN');
         }
 
         switch (strtoupper($type)) {
             case 'JSON':
                 // 返回JSON数据格式到客户端 包含状态信息
                 header('Content-Type:application/json; charset=utf-8');
                 $data = json_encode($data, $json_option);
                 break;
             case 'JSONP':
                 // 返回JSON数据格式到客户端 包含状态信息
                 header('Content-Type:application/json; charset=utf-8');
                 $handler = isset($_GET[C('VAR_JSONP_HANDLER')]) ? $_GET[C('VAR_JSONP_HANDLER')] : C('DEFAULT_JSONP_HANDLER');
                 $data    = $handler . '(' . json_encode($data, $json_option) . ');';
                 break;
             case 'EVAL':
                 // 返回可执行的js脚本
                 header('Content-Type:text/html; charset=utf-8');
                 break;
         }
         exit($data);
     }
 
 
     // 继续重写其他方法，使用模型类替换数据库操作
 }
 